<template>
  <span style="cursor: pointer">
    <el-upload
      :action="uploadUrl"
      :data="qiniuData"
      :show-file-list="false"
      :on-success="onUploadSuccess"
      :on-error="onUploadError"
      :before-upload="onBeforeUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" width="200" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </span>
</template>

<script>
import * as qiniu from 'qiniu-js'
import utils from '@/libs/util.gaed'
import settings from '@/setting'
export default {
  props: {
    // 用于v-model的模式对外传递数据
    value: {
      type: String,
      require: true
    },
    type: {
      type: String,
      require: true
    },
    // 本行的所有数据，此字段不需要额外配置
    scope: {
      default: null
    }
  },
  data () {
    return {
      uploadUrl: '',
      echoUrl: '',
      qiniuData: {
        key: '',
        token: settings.qiniu.token
      }
    }
  },
  computed: {
    imageUrl: {
      get: function () {
        return this.value
      },
      // setter
      set: function (newValue) {
        this.echoUrl = newValue
      }
    }
  },
  mounted () {
    let config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 6,
      region: qiniu.region.z0
    }
    utils.fetchData('/third/uptoken').then(res => {
      console.log('获取到的数据为：', res)
      this.qiniuData.token = res.uptoken
    }).catch(err => {
      console.warn(err)
    })
    qiniu.getUploadUrl(config, settings.qiniu.token).then(res => {
      console.log('上传URL为：', res)
      this.uploadUrl = res
    })
    console.log('传入的value为：', this.value)
    // this.imageUrl = this.value
  },
  methods: {
    onUploadSuccess (res, file) {
      this.imageUrl = settings.qiniu.imageEcho + res.key
      console.log('上传成功')
      this.$emit('input', this.echoUrl)
    },
    onUploadError (res, file) {
      console.log('上传失败: ', res)
    },
    onBeforeUpload (file) {
      this.qiniuData.key = file.name
    }
  }
}
</script>
